'头节点
Dim ListHead As ListItem


Function Find(ByVal varItem As Variant, _
ByRef listCurrent As ListItem, _
ByRef listPrevious As ListItem) As Boolean
    
    Dim bFound As Boolean
    '初始化当前节点为头节点
    bFound = False
    Set listPrevious = Nothing
    Set listCurrent = ListHead
    '链表不为空则循环
    Do While Not listCurrent Is Nothing
        '查找给定的值,如果当前值不是,则后移
        With listCurrent
            If varItem > .Value Then
                Set listPrevious = listCurrent
                Set listCurrent = .NextItem
            Else
                Exit Do
            End If
        End With
    Loop
    '如果找到,则返回True
    If Not listCurrent Is Nothing Then
        bFound = (listCurrent.Value = varItem)
    End If
    Find = bFound
End Function



'添加节点元素
Public Sub Add(varValue As Variant)
    Dim listNew As New ListItem
    Dim listCurrent As ListItem
    Dim listPrevious As ListItem
    '新元素值
    listNew.Value = varValue
    '调用Find函数确定新元素位置
    Call Find(varValue, listCurrent, listPrevious)
    '如果链表存在节点,则将新元素节点链接到相应位置
    If Not listPrevious Is Nothing Then
        Set listNew.NextItem = listPrevious.NextItem
        Set listPrevious.NextItem = listNew
    Else
    '链表不存在节点,则该元素为头节点
        Set listNew.NextItem = ListHead
        Set ListHead = listNew
    End If
End Sub


'删除节点元素
Public Function Delete(varItem As Variant) As Boolean
    Dim listCurrent As ListItem
    Dim listPrevious As ListItem
    Dim bFound As Boolean
    '调用Find函数确定删除元素的位置
    bFound = Find(varItem, listCurrent, listPrevious)
    If bFound Then
        '删除中间的节点元素
        If Not listPrevious Is Nothing Then
            Set listPrevious.NextItem = listCurrent.NextItem
        Else
        '删除头节点元素
            Set ListHead = listCurrent.NextItem
        End If
    End If
    Delete = bFound
End Function

'遍历链表
Public Sub ListAllItem()
    Dim listCurrent As ListItem
    Set listCurrent = ListHead
    '从头节点开始遍历
    Do While Not listCurrent Is Nothing
        Debug.Print listCurrent.Value
        Set listCurrent = listCurrent.NextItem
    Loop
End Sub


